import 'dart:math';

import 'package:extended_text_field/extended_text_field.dart';
import 'package:flutter/material.dart';
import 'package:hxdj/common/components/my_tap_widget.dart';
import 'package:hxdj/common/components/my_text.dart';
import 'package:hxdj/common/my_get_it.dart';
import 'package:hxdj/common/my_header_global.dart';
import 'package:hxdj/common/my_keyboard_visibility.dart';
import 'package:hxdj/common/my_optimize_utils.dart';
import 'package:hxdj/common/utils/my_device.dart';
import 'package:hxdj/message/rongcloud/rc_chat/controller/rc_chat_base_input_controller.dart';

class MyBaseChatInputWidget extends StatefulWidget {
  final RCChatInputTextFieldController textFieldController;
  final TextEditingController textEditingController;
  final FocusNode focusNode;
  final bool isShowAudio, isShowEmoji, isShowPanel;
  final Function(String) onSendText;

  const MyBaseChatInputWidget({
    super.key,
    required this.textEditingController,
    required this.focusNode,
    this.isShowAudio = false,
    this.isShowEmoji = false,
    this.isShowPanel = false,
    required this.onSendText,
    required this.textFieldController,
  });

  @override
  State<MyBaseChatInputWidget> createState() => _MyBaseChatInputWidgetState();
}

class _MyBaseChatInputWidgetState extends State<MyBaseChatInputWidget> {
  final MySettingModel settingModel = serviceLocator<MySettingModel>();

  bool showMore = false;
  bool showMoreButton = true;
  bool showSendSoundText = false;
  bool showEmojiPanel = false;
  bool showKeyboard = false;
  Function? setKeyboardHeight;
  double? bottomPadding;

  @override
  void initState() {
    super.initState();
    widget.textFieldController.addListener(
      () {
        final actionType = widget.textFieldController.actionType;
        if (actionType == MyTextFieldActionType.hideAllPanel) {
          hideAllPanel();
        }
      },
    );
  }

  @override
  dispose() {
    super.dispose();    
  }

  //隐藏所有功能
  hideAllPanel() {
    widget.focusNode.unfocus();
    if (showKeyboard != false || showMore != false || showEmojiPanel != false) {
      setState(() {
        showKeyboard = false;
        showMore = false;
        showEmojiPanel = false;
      });
    }
  }

  _openMore() {
    if (!showMore) {
      widget.focusNode.unfocus();
    }
    setState(() {
      showKeyboard = false;
      showEmojiPanel = false;
      showSendSoundText = false;
      showMore = !showMore;
    });
  }

  double _getBottomHeight() {
    if (showKeyboard) {
      final currentKeyboardHeight = MediaQuery.of(context).viewInsets.bottom;
      double originHeight = settingModel.keyboardHeight;
      if (currentKeyboardHeight != 0) {
        if (currentKeyboardHeight >= originHeight) {
          originHeight = currentKeyboardHeight;
        }
        if (setKeyboardHeight != null) {
          setKeyboardHeight!(currentKeyboardHeight);
        }
      }
      final height = originHeight != 0 ? originHeight : currentKeyboardHeight;
      return height;
    } else if (showMore || showEmojiPanel) {
      return 248.0 + (bottomPadding ?? 0.0);
    } else if (widget.textEditingController.text.length >= 46 && showKeyboard == false) {
      return 25 + (bottomPadding ?? 0.0);
    } else {
      return bottomPadding ?? 0;
    }
  }

  _openEmojiPanel() {
    showKeyboard = showEmojiPanel;
    if (showEmojiPanel) {
      widget.focusNode.requestFocus();
    } else {
      widget.focusNode.unfocus();
    }

    setState(() {
      showMore = false;
      showSendSoundText = false;
      showEmojiPanel = !showEmojiPanel;
    });
  }

  Widget _getBottomContainer() {
    if (showEmojiPanel) {
      return Container(
        child: const MyText("表情视图"),
      );
    }

    if (showMore) {
      return Container(
        child: const MyText("功能视图"),
      );
    }

    return const SizedBox(height: 0);
  }

  @override
  Widget build(BuildContext context) {
    setKeyboardHeight ??= MyOptimizeUtils.debounce((height) {
      settingModel.keyboardHeight = height;
    }, const Duration(seconds: 1));

    bottomPadding = MediaQuery.of(context).padding.bottom;

    return GestureDetector(
        onTap: () {},
        child: Column(children: [
          Container(
              decoration: const BoxDecoration(color: MyColours.bgColor, boxShadow: <BoxShadow>[
                BoxShadow(
                  color: MyColours.color2E2626,
                  offset: Offset(0.0, -13),
                  blurRadius: 12.0,
                  spreadRadius: -9.0,
                )
              ]),
              child: Column(
                children: [
                  Container(
                    padding: EdgeInsets.symmetric(vertical: 8.h),
                    constraints: const BoxConstraints(minHeight: 50),
                    child: Row(
                      children: [
                        if (widget.isShowAudio)
                          MyTapWidget(
                            onTap: () async {
                              showKeyboard = showSendSoundText;
                              if (showSendSoundText) {
                                widget.focusNode.requestFocus();
                              }
                            },
                            child: Padding(
                              padding: EdgeInsets.only(right: 10.w, left: 10.w),
                              child: MyImage(
                                imageName: "ic_address",
                                width: 30.w,
                              ),
                            ),
                          ),
                        Expanded(
                            child: showSendSoundText
                                ? const MyText("按着说话")
                                : MyKeyboardVisibility(
                                    onChanged: (bool visibility) {
                                      if (showKeyboard != visibility) {
                                        setState(() {
                                          showKeyboard = visibility;
                                        });
                                      }
                                    },
                                    child: ClipRRect(
                                      //圆角图片
                                      borderRadius: BorderRadius.circular(5),
                                      child: Padding(
                                        padding: EdgeInsets.only(left: 15.w, right: 15.w),
                                        child: ExtendedTextField(
                                          focusNode: widget.focusNode,
                                          textInputAction:
                                              MyDevice.isAndroid ? TextInputAction.newline : TextInputAction.send,
                                          maxLines: 4,
                                          minLines: 1,
                                          keyboardType: TextInputType.multiline,
                                          onEditingComplete: () {
                                            if (showKeyboard) {
                                              widget.focusNode.requestFocus();
                                            }
                                            widget.onSendText("");
                                            widget.textEditingController.clear();
                                          },
                                          textAlignVertical: TextAlignVertical.top,
                                          decoration: const InputDecoration(
                                              border: InputBorder.none,
                                              hintStyle: TextStyle(
                                                // fontSize: 10,
                                                color: Color(0xffAEA4A3),
                                              ),
                                              fillColor: Colors.white,
                                              filled: true,
                                              isDense: true,
                                              hintText: '请输入消息...'),
                                          controller: widget.textEditingController,
                                          onTap: () {
                                            showKeyboard = true;

                                            setState(() {
                                              showEmojiPanel = false;
                                              showMore = false;
                                            });
                                          },
                                        ),
                                      ),
                                    ),
                                  )),
                        if (widget.isShowEmoji)
                          MyTapWidget(
                            onTap: () async {
                              _openEmojiPanel();
                            },
                            child: Padding(
                              padding: EdgeInsets.only(right: 10.w, left: 10.w),
                              child: MyImage(
                                imageName: "ic_address",
                                width: 30.w,
                              ),
                            ),
                          ),
                        if (widget.isShowPanel)
                          MyTapWidget(
                            onTap: () async {
                              _openMore();
                            },
                            child: Padding(
                              padding: EdgeInsets.only(right: 10.w),
                              child: MyImage(
                                imageName: "ic_address",
                                width: 30.w,
                              ),
                            ),
                          ),
                        // Padding(
                        //   padding: EdgeInsets.only(left: 10.w),
                        //   child: SizedBox(
                        //     height: 32.0,
                        //     child: ElevatedButton(
                        //       onPressed: () {
                        //         if (showKeyboard) {
                        //           widget.focusNode.requestFocus();
                        //         }
                        //         if (widget.textEditingController.text.isEmpty) {
                        //           setState(() {
                        //             showMoreButton = true;
                        //           });
                        //         }
                        //       },
                        //       child: const Text("发送"),
                        //     ),
                        //   ),
                        // ),
                      ],
                    ),
                  ),
                  AnimatedContainer(
                    duration: Duration(milliseconds: (showKeyboard && MyDevice.isAndroid) ? 200 : 340),
                    curve: Curves.fastOutSlowIn,
                    height: max(_getBottomHeight(), 0.0),
                    child: ListView(
                      physics: const NeverScrollableScrollPhysics(),
                      children: [_getBottomContainer()],
                    ),
                  ),
                ],
              ))
        ]));
  }
}

//   @override
//   void initState() {
//     super.initState();
//   }

//   void setSendButton() {
//     final value = widget.textEditingController.text;
//     if (MyDevice.isAndroid) {
//       if (value.isEmpty && showMoreButton != true) {
//         setState(() {
//           showMoreButton = true;
//         });
//       } else if (value.isNotEmpty && showMoreButton == true) {
//         setState(() {
//           showMoreButton = false;
//         });
//       }
//     }
//   }

//   hideAllPanel() {
//     widget.focusNode.unfocus();
//     widget.currentCursor == null;
//     if (showKeyboard != false || showMore != false || showEmojiPanel != false) {
//       setState(() {
//         showKeyboard = false;
//         showMore = false;
//         showEmojiPanel = false;
//       });
//     }
//   }



//   _debounce(
//     Function(String text) fun, [
//     Duration delay = const Duration(milliseconds: 30),
//   ]) {
//     Timer? timer;
//     return (String text) {
//       if (timer != null) {
//         timer?.cancel();
//       }

//       timer = Timer(delay, () {
//         fun(text);
//       });
//     };
//   }

//   @override
//   Widget Build(BuildContext context) {
//     setKeyboardHeight ??= MyOptimizeUtils.debounce((height) {
//       settingModel.keyboardHeight = height;
//     }, const Duration(seconds: 1));

//     final debounceFunc = _debounce((value) {
//       if (MyDevice.isAndroid) {
//         if (value.isEmpty && showMoreButton != true) {
//           setState(() {
//             showMoreButton = true;
//           });
//         } else if (value.isNotEmpty && showMoreButton == true) {
//           setState(() {
//             showMoreButton = false;
//           });
//         }
//       }
//       if (widget.onChanged != null) {
//         widget.onChanged!(value);
//       }
//       widget.handleAtText(value);
//       widget.handleSendEditStatus(value, true);
//       final isEmpty = value.isEmpty;
//       if (isEmpty) {
//         widget.handleSoftKeyBoardDelete();
//       }
//     }, const Duration(milliseconds: 80));

//     final MediaQueryData data = MediaQuery.of(context);
//     EdgeInsets padding = data.padding;
//     if (bottomPadding == null || padding.bottom > bottomPadding!) {
//       bottomPadding = padding.bottom;
//     }

//     return GestureDetector(
//       onTap: () {},
//       child: Column(
//         children: [
//           Container(
//             color:MyColours.appMain,
//             child: Column(
//               children: [
//                 Container(
//                   padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16),
//                   constraints: const BoxConstraints(minHeight: 50),
//                   child: Row(
//                     children: [
//                       if (widget.forbiddenText != null)
//                         Expanded(
//                             child: Container(
//                           height: 35,
//                           color: MyColours.randomARGB(),
//                           alignment: Alignment.center,
//                           child: Text(
//                             "widget.forbiddenText!",
//                             textAlign: TextAlign.center,
//                             style: TextStyle(
//                               fontWeight: FontWeight.bold,
//                               fontSize: 16,
//                               color: MyColours.randomARGB(),
//                             ),
//                           ),
//                         )),
//                       if (widget.showSendAudio && widget.forbiddenText == null)
//                         InkWell(
//                           onTap: () async {
//                             showKeyboard = showSendSoundText;
//                             if (showSendSoundText) {
//                               widget.focusNode.requestFocus();
//                             }
//                           },
//                           child: MyText("发送语音的按钮"),
//                         ),
//                       if (widget.forbiddenText == null)
//                         const SizedBox(
//                           width: 10,
//                         ),
//                       if (widget.forbiddenText == null)
//                         Expanded(
//                           child: showSendSoundText
//                               ? MyText("按着说话")
//                               : MyKeyboardVisibility(
//                                   child:MyText("输入框"),
                                  
//                                   //  ExtendedTextField(
//                                   //     maxLines: 4,
//                                   //     minLines: 1,
//                                   //     focusNode: widget.focusNode,
//                                   //     onChanged: debounceFunc,
//                                   //     onTap: () {
//                                   //       showKeyboard = true;
//                                   //       widget.goDownBottom();
//                                   //       setState(() {
//                                   //         showEmojiPanel = false;
//                                   //         showMore = false;
//                                   //       });
//                                   //     },
//                                   //     keyboardType: TextInputType.multiline,
//                                   //     textInputAction:
//                                   //         MyDevice.isAndroid ? TextInputAction.newline : TextInputAction.send,
//                                   //     onEditingComplete: () {
//                                   //       widget.onSubmitted();
//                                   //       if (showKeyboard) {
//                                   //         widget.focusNode.requestFocus();
//                                   //       }
//                                   //       setState(() {
//                                   //         if (widget.textEditingController.text.isEmpty) {
//                                   //           showMoreButton = true;
//                                   //         }
//                                   //       });
//                                   //     },
//                                   //     textAlignVertical: TextAlignVertical.top,
//                                   //     decoration: InputDecoration(
//                                   //         border: InputBorder.none,
//                                   //         hintStyle: const TextStyle(
//                                   //           // fontSize: 10,
//                                   //           color: Color(0xffAEA4A3),
//                                   //         ),
//                                   //         fillColor: Colors.white,
//                                   //         filled: true,
//                                   //         isDense: true,
//                                   //         hintText: widget.hintText ?? ''),
//                                   //     controller: widget.textEditingController,
//                                   //     specialTextSpanBuilder: DefaultSpecialTextSpanBuilder(
//                                   //       isUseQQPackage: (widget.model.chatConfig.stickerPanelConfig
//                                   //                   ?.useTencentCloudChatStickerPackage ??
//                                   //               true) ||
//                                   //           widget.isUseDefaultEmoji,
//                                   //       isUseTencentCloudChatPackage: widget.model.chatConfig.stickerPanelConfig
//                                   //               ?.useTencentCloudChatStickerPackage ??
//                                   //           true,
//                                   //       customEmojiStickerList: widget.customEmojiStickerList,
//                                   //       showAtBackground: true,
//                                   //     )),
//                                   onChanged: (bool visibility) {
//                                     if (showKeyboard != visibility) {
//                                       setState(() {
//                                         showKeyboard = visibility;
//                                       });
//                                     }
//                                   }),
//                         ),
//                       if (widget.forbiddenText == null)
//                         const SizedBox(
//                           width: 10,
//                         ),
//                       if (widget.showSendEmoji && widget.forbiddenText == null)
//                         InkWell(
//                             onTap: () {
//                               _openEmojiPanel();
//                               widget.goDownBottom();
//                             },
//                             child: MyText("按钮")),
//                       if (widget.forbiddenText == null)
//                         const SizedBox(
//                           width: 10,
//                         ),
//                       if (widget.showMorePanel && widget.forbiddenText == null && showMoreButton)
//                         InkWell(
//                           onTap: () {
//                             // model.sendCustomMessage(data: "a", convID: model.currentSelectedConv, convType: model.currentSelectedConvType == 1 ? ConvType.c2c : ConvType.group);
//                             _openMore();
//                             widget.goDownBottom();
//                           },
//                           child: MyText("按钮")),
//                         ),
//                       if ((MyDevice.isAndroid) && !showMoreButton)
//                         SizedBox(
//                           height: 32.0,
//                           child: ElevatedButton(
//                             onPressed: () {
//                               widget.onSubmitted();
//                               if (showKeyboard) {
//                                 widget.focusNode.requestFocus();
//                               }
//                               if (widget.textEditingController.text.isEmpty) {
//                                 setState(() {
//                                   showMoreButton = true;
//                                 });
//                               }
//                             },
//                             child: Text("发送"),
//                           ),
//                         ),
//                     ],
//                   ),
//                 ),
//                 AnimatedContainer(
//                   duration: Duration(milliseconds: (showKeyboard && MyDevice.isAndroid) ? 200 : 340),
//                   curve: Curves.fastOutSlowIn,
//                   height: max(_getBottomHeight(), 0.0),
//                   child: ListView(
//                     physics: const NeverScrollableScrollPhysics(),
//                     children: [_getBottomContainer()],
//                   ),
//                 ),
//               ],
//             )
//     );

//   }    
      
// }
